import React from 'react';
import FieldList from './fieldsList';
import CommonListsIndex from 'src/components/CommonLists/index';
import FilterTool from 'src/components/FilterTool';
import services from 'src/services/api';
import { message } from 'antd';
import './index.less'

class FieldIndex extends CommonListsIndex {
  constructor(props) {
    super(props);
    this.api = 'indicator';
    this.listsComponent = FieldList;
    this.queryParams = {};
    this.initQueryPanigation = {
      current_page: 1,
      page_size: 10,
    };
    this.state = {
      field_ids: [], // 已勾选的字段，复制要用
      applications: [],
      events: [],
      products: [],
      selectedRowKeys: [],
      app_id: '',
      event_id: '',
      product_id: '',
      filterItems: [],
      mapEventList: []
    };
    this.queryPanigation = {
      current_page: 1,
      page_size: 10,
    };

    this.queryTableParams = {};

    this.model_width = 600;
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    const current = nextProps.mapping_relation.find((it) => {
      return (
        it.param_id === nextProps.activeRow.param_id &&
        it.column_code === nextProps.activeRow.column_code &&
        it.app_id === this.state.app_id &&
        it.event_id === this.state.event_id
      );
    });
    if (current) {
      this.setState({
        selectedRowKeys: [current.var_id_type],
      });
    } else {
      this.setState({
        selectedRowKeys: [],
      });
    }
  }

  componentDidMount() {
    this.getAppCodeList();
    if (this.props.actionType === 'child-update') {
      const { app_id, product_id, event_id } = this.props.childRecord;
      this.setState({ app_id, product_id, event_id });
      this.queryParams = { app_id, product_id, event_id };
      this.getEventCodeList(app_id, product_id);
      this.getProductCodeList(app_id, event_id);
    } else {
      this.getProductCodeList();
      this.getEventByInterface();
    }
  }

  // 获取当前接口下已映射的事件
  getEventByInterface = () => {
    const { model_list_id } = this.props.record;
    services.model.mapEvent({ model_list_id }).then((res) => {
      const { code, msg, data } = res;
      if (!code) {
        this.setState({ mapEventList: data });
      } else {
        message.error(msg);
      }
    });
  };

  updateFilterItems = () => {
    const { app_id, product_id, event_id } = this.state;
    this.setState({
      filterItems: [
        {
          type: 'Select',
          key: 'app_id',
          name: 'app_id',
          label: '渠道',
          defaultValue: app_id,
          span: 12,
          options: [
            ...this.state.applications.map((item) => {
              return {
                value: item.app_id,
                name: item.app_name,
              };
            }),
          ],
          onChange: this.onAppChangeSelect,
        },
        {
          type: 'Select',
          key: 'product_id',
          name: 'product_id',
          label: '产品',
          defaultValue: product_id,
          span: 12,
          options: [
            ...this.state.products.map((item) => {
              return {
                value: item.product_id,
                name: item.product_name,
              };
            }),
          ],
          onChange: this.onProductChangeSelect,
          allowClear: true,
        },
        {
          type: 'Select',
          key: 'event_id',
          name: 'event_id',
          label: '事件',
          defaultValue: event_id,
          span: 12,
          options: [
            ...this.state.events.map((item) => {
              return {
                value: item.event_id,
                name: item.event_name,
              };
            }),
          ],
          onChange: this.onEventChangeSelect,
        },
        {
          type: 'Search',
          key: 'keyword',
          name: 'keyword',
          defaultValue: '',
          span: 12,
          placeholder: '请输入指标名|指标Code进行搜索',
        },
      ],
    });
  };
  getProductCodeList = (app_id, event_id) => {
    services.product.getProductCodeList(event_id ? { app_id, event_id } : {}).then((res) => {
      if (res.code === 0) {
        // 当event_id存在，默认回写productId
        if (event_id) {
          const product_id = res.data.length === 1 ? res.data[0].product_id : undefined;
          this.setState({
            product_id,
          });
        }
        this.setState({
          products: res.data,
        });
        this.updateFilterItems();
      }
    });
  };
  getAppCodeList = ({ product_id = -1, event_id = -1 } = {}) => {
    services.application.getAppCodeList({ product_id, event_id }).then((res) => {
      if (res.code === 0) {
        // res.data.shift();
        this.setState({
          applications: res.data,
        },
         this.updateFilterItems
        );
      }
    });
  };

  getEventCodeList = (app_id, product_id) => {
    services.event.getEventCodeList({ app_id, product_id }).then((res) => {
      if (res.code === 0) {
        // res.data.shift();
        this.setState({
          events: res.data,
        }, () => {
          this.updateFilterItems();
          this.refs.filterTool.handleChange('event_id', '');
        });
      }
    });
  };

  freshQueryList = () => {
    const { event_id } = this.queryParams;
    if (event_id) {
      if (this.state.mapEventList.includes(event_id)) {
        this.clearList();
        return message.warning('该事件下已存在映射关系,请重新选择事件！');
      }
      this.queryList({ ...this.queryParams, ...this.queryTableParams, ...this.queryPanigation });
      // this.props.updateAppAndEvent(this.state.app_id, event_id);
    } else {
      this.clearList();
    }
  };

  // 列表
  queryList = (params) => {
    services.model.getFieldFeature(params).then((res) => {
      if (res.code === 0) {
        this.setState({
          ...res.data,
          list: res.data.list.map((it) => {
            it.var_id_type = it.var_id + '-' + it.var_type;
            return it;
          }),
        });

        // this.props.updateFieldsData(res.data.list);
      } else {
        message.error(res.msg);
      }
    });
  };

  refreshPanagaition = (params) => {
    this.queryPanigation = {
      ...this.queryPanigation,
      ...params,
    };
  };

  refreshTableFilter = (params) => {
    this.queryTableParams = { ...this.queryTableParams, ...params };
    this.refreshPanagaition(this.initQueryPanigation);
    this.freshQueryList();
  };
 // onProductChangeSelect
  onProductChangeSelect = (_, e) => {
    if (!e) this.getProductCodeList();
    this.setState(
      {
        event_id: '',
        product_id: e,
        selectedRowKeys: this.state.selectedRowKeys.splice(0),
      },
      () => {
        const { app_id, event_id } = this.state;
        this.getEventCodeList(app_id, e);
        this.refs.filterTool.handleChange('product_id', e);
        this.props.updateAppAndEvent(app_id, event_id, e, true);
      }
    );
  };
  refreshFilter = (params, key) => {
    if (this.props.actionType === 'child-update') {
      const { keyword } = params;
      this.queryParams = { ...this.queryParams, keyword };
    } else {
      this.queryParams = params;
    }
    this.refreshPanagaition(this.initQueryPanigation);
    if (key === 'event_id' || key === 'keyword') {
      this.freshQueryList();
    }
    // this.queryParams = params;
    // this.refreshPanagaition(this.initQueryPanigation);
    // if (key==='event_id' || key === 'keyword') {
    //   this.freshQueryList();
    // }
  };
  // onAppChangeSelect
  onAppChangeSelect = (name, e) => {
    this.setState({
      event_id: '',
      app_id: e,
      selectedRowKeys: this.state.selectedRowKeys.splice(0),
    }, () => {
      const { product_id, event_id } = this.state;
      this.getEventCodeList(e, product_id);
      this.props.updateAppAndEvent(e, event_id, product_id, true);
    });
  };
  // onEventChangeSelect
  onEventChangeSelect = (name, e) => {
    this.setState({
      event_id: e,
      selectedRowKeys: this.state.selectedRowKeys.splice(0),
    },
    () => {
      const { app_id, product_id } = this.state;
      this.getProductCodeList(app_id, e);
      this.props.updateAppAndEvent(app_id, e, product_id, true);
    });
  };

  render() {
    const ListsComponent = this.listsComponent;
    // 字段选择配置
    const rowSelection = {
      columnWidth: 30,
      onChange: (selectedRowKeys, selectedRows) => {
        let currentSelectedRow = {};
        if (selectedRowKeys.length > 0) {
          selectedRowKeys.splice(0, selectedRowKeys.length - 1);
          currentSelectedRow = selectedRows.find((item) => item.var_id_type === selectedRowKeys[0]);
        }
        this.props.updateMap(currentSelectedRow, this.state.app_id, this.state.event_id, this.state.product_id);
        this.setState({
          selectedRowKeys,
        });
      },
      getCheckboxProps: (record) => {
        const currentActiveRow = this.props.mapping_relation.find((it) => {
          return (
            it.param_id === this.props.activeRow.param_id &&
            it.column_code === this.props.activeRow.column_code &&
            it.app_id === this.state.app_id &&
            it.event_id === this.state.event_id
          );
        });
        const isCurrent = currentActiveRow && currentActiveRow.var_id_type === record.var_id_type
        const isSelected = this.props.mapping_relation.find((it) => {
          // 返回app_id,event_id事件下已经被选过了的对象
          return (
            it.var_id_type === record.var_id_type &&
            it.app_id === this.state.app_id &&
            it.event_id === this.state.event_id
          );
        });
        // const disabled = currentActiveRow
        //   ? isSelected && currentActiveRow.var_id_type !== record.var_id_type
        //   : isSelected;
        const disabled = (!isCurrent && isSelected) ? true : false
        return {
          disabled: !this.props.activeRow || this.props.disabled || disabled,
          name: record.var_id_type,
        };
      },
      hideDefaultSelections: true,
      selectedRowKeys: this.state.selectedRowKeys,
    };
    return (
      <div className='fields-model'>
        <FilterTool
          ref='filterTool'
          data={this.state.filterItems}
          colNum={3}
          query={this.freshQueryList}
          refreshFilter={this.refreshFilter}
          isOnChange={true}
          isNotShowExpened={true}
          isSearchNotSpaceBetween={true}
          disabled={this.props.actionType === 'child-update'}
        />
        <div style={{ marginTop: '10px' }} className='field-map-table'>
          <ListsComponent
            {...this.state}
            rowKey='var_id_type'
            applications={this.state.applications}
            edit={this.edit}
            queryList={this.freshQueryList}
            refreshTableFilter={this.refreshTableFilter}
            onChangePagination={this.onChangePagination}
            showDetail={this.showDetail}
            rowSelection={rowSelection}
            queryTableParams={this.queryTableParams}
            paginationSize='small'
            showSizeChanger={false}
          />
        </div>
      </div>
    );
  }
}

export default FieldIndex;
